package com.czk.classreader.method.addcode;

import com.czk.utils.FileUtil;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;

/**
 * 在方法进入和退出时都添加都添加代码方法一
 *
 * @Author:ChenZhangKun
 * @Date: 2021/8/16 17:53
 */
public class MethodEnterAndExitCore_1 {
    public static void main(String[] args) {
        String path = "F:\\IdeaProjects\\asm\\target\\classes\\com\\czk\\sample\\Test.class";
        byte[] bytes1 = FileUtil.readBytes(path);
        // 阅读
        ClassReader cr = new ClassReader(bytes1);
        // 写
        ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
        // 串联
        int api = Opcodes.ASM9;
        ClassVisitor cv1 = new MethodEnterVisitor(api, cw);
        // 串联两个visitor
        ClassVisitor cv2 = new MethodExitVisitor(api, cv1);
        ClassVisitor cv = cv2;
        // 结合
        int parsingOptions = ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES;
        cr.accept(cv, parsingOptions);
        byte[] bytes = cw.toByteArray();
        FileUtil.writeBytes(path, bytes);
    }
}
